package com.ht.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ht.shortlink.admin.common.biz.user.UserContext;
import com.ht.shortlink.admin.common.convention.exception.ClientException;
import com.ht.shortlink.admin.common.convention.exception.ServiceException;
import com.ht.shortlink.admin.dao.entity.UserDO;
import com.ht.shortlink.admin.dao.mapper.UserMapper;
import com.ht.shortlink.admin.dto.req.UserLoginReqDTO;
import com.ht.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.ht.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.ht.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.ht.shortlink.admin.dto.resp.UserRespDTO;
import com.ht.shortlink.admin.service.IGroupService;
import com.ht.shortlink.admin.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.ht.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static com.ht.shortlink.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static com.ht.shortlink.admin.common.convention.errorcode.BaseErrorCode.USER_NAME_EXIST_ERROR;
import static com.ht.shortlink.admin.common.enums.UserErrorCode.*;

/**
 *  用户接口实现层
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements IUserService {
    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final IGroupService groupService;

    @Override
    public UserRespDTO getUserByUsername(String username) {
        UserDO user = lambdaQuery().eq(UserDO::getUsername, username).one();
        if(user == null){
            throw new ServiceException(USER_NAME_NOT_EXIST_ERROR);
        }


        return BeanUtil.copyProperties(user, UserRespDTO.class);
    }

    @Override
    public Boolean hasUsername(String username) {
        return userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO requestParam) {
        String username = requestParam.getUsername();
        // 1、判断用户是否存在
        if(userRegisterCachePenetrationBloomFilter.contains(username)){
            // 2、存在，抛异常
            throw new ClientException(USER_NAME_EXIST_ERROR);
        }

        // 3、不存在，加锁，加入到数据库中
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + username);
        try{
            // 防止用相同用户名短时间内大量访问
            if(lock.tryLock()){
                boolean save = save(BeanUtil.copyProperties(requestParam, UserDO.class));
                if(save){
                    // 4、保存成功，加入到缓存中
                    userRegisterCachePenetrationBloomFilter.add(username);
                    // 5、创建默认分组
                    groupService.add(requestParam.getUsername(), "默认分组");
                }else {
                    throw new ServiceException(USER_SAVE_ERROR);
                }
            }else {
                throw new ClientException(USER_NAME_EXIST_ERROR);
            }
        } catch (DuplicateKeyException ex){
            // username唯一索引报错
            throw new ClientException(USER_NAME_EXIST_ERROR);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void userInfoUpdate(UserUpdateReqDTO requestParam) {
        // 1、校验修改的用户信息是不是当前登录用户的信息
        if(!UserContext.getUsername().equals(requestParam.getUsername())){
            throw new ClientException(USER_UPDATE_ERROR);
        }
        // 2、校验用户名是否存在
        UserDO userDO = lambdaQuery().eq(UserDO::getUsername, requestParam.getUsername()).one();
        if(userDO == null){
            throw new ClientException(USER_NAME_NOT_EXIST_ERROR);
        }
        // 3、修改
        LambdaUpdateWrapper<UserDO> wrapper = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername());

        update(BeanUtil.copyProperties(requestParam, UserDO.class), wrapper);
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        // 1、检验用户名和密码是否正确
        UserDO userDO = lambdaQuery()
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword())
                .eq(UserDO::getDelFlag, 0)
                .one();
        if (userDO == null) {
            throw new ClientException(USER_LOGIN_NAME_PASS_ERROR);
        }

        String tokenKey = USER_LOGIN_KEY + userDO.getUsername();

        // 2、防止用户重复登录,已经登录了则返回原来的token
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(tokenKey);
        if(CollUtil.isNotEmpty(entries)){
            String token = entries.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException(USER_LOGIN_ERROR));
            return new UserLoginRespDTO(token);
        }

        // 3、生成token
        String uuid = UUID.randomUUID(false).toString();

        // 4、token 保存到缓存中,并设置30分钟过期时间
        stringRedisTemplate.opsForHash().put(tokenKey, uuid, JSONUtil.toJsonStr(userDO));
        stringRedisTemplate.expire(tokenKey, 30L, TimeUnit.MINUTES);

        return new UserLoginRespDTO(uuid);
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY + username, token) != null;
    }

    @Override
    public void logout(String username, String token) {
        if(checkLogin(username, token)){
            stringRedisTemplate.delete(USER_LOGIN_KEY + username);
        }else{
            throw new ClientException(USER_NOT_LOGIN_ERROR);
        }
    }
}
